% 1、读取iris数据集
% This example shows how to construct a k-nearest neighbor classifier for
% the Fisher iris data
clear 
load fisheriris
X = meas;
Y = species;
N = numel(Y);

% 2、分割数据集
rng(33);
testsize = 0.25;
randidx = randperm(N);
X_train = X(randidx(1:round(N*(1-testsize))),:);
Y_train = Y(randidx(1:round(N*(1-testsize))),:);
X_test = X(randidx(1+round(N*(1-testsize)):end),:);
Y_test = Y(randidx(1+round(N*(1-testsize)):end),:);

% 3、KNN
Mdl = fitcknn(X_train, Y_train, 'NumNeighbors', 1);

% 4、预测
% Predict the classification of an average flower
Y_predict = predict(Mdl, X_test);
Ntest = numel(Y_test);
accuracy = sum(strcmp(Y_predict, Y_test))/Ntest;

